import * as api from '@/api/api'
import {Base64} from 'js-base64'

export function postBase64Img (base64Data, token, key, callback) {
  let pic = base64Data.replace(/^.*?,/, '')
  let url = 'http://upload.qiniu.com/putb64/-1' // 非华东空间需要根据注意事项 1 修改上传域名
  if (key !== null) {
    url += '/key/' + Base64.encode(key)
  }
  let xhr = new XMLHttpRequest()
  xhr.onreadystatechange = () => {
    if (xhr.readyState === 4) {
      let res = JSON.parse(xhr.responseText)
      api.post({
        url: '/qn/saveTemp',
        data: {key: res.key},
        success: data => {
          if (data.code === 0) {
            callback(res.key)
          } else {
            console.log(data)
          }
        }
      })
    }
  }
  xhr.open('POST', url, true)
  xhr.setRequestHeader('Content-Type', 'application/octet-stream')
  xhr.setRequestHeader('Authorization', 'UpToken ' + token)
  xhr.send(pic)
}
